package com.reebake.ideal.permission.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.reebake.ideal.permission.entity.Menu;
import com.reebake.ideal.permission.entity.RoleMenu;
import com.reebake.ideal.permission.service.MenuService;
import com.reebake.ideal.permission.service.PermissionAuthService;
import com.reebake.ideal.permission.service.RoleMenuService;
import com.reebake.ideal.permission.vo.MenuVO;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/menu")
@RequiredArgsConstructor
public class MenuPlusController {
    private final MenuService menuService;
    private final RoleMenuService roleMenuService;
    private final PermissionAuthService permissionAuthService;

    @GetMapping("{menuType}/all")
    public List<MenuVO> queryAllByMenuType(@PathVariable String menuType){
        LambdaQueryWrapper<Menu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Menu::getMenuType, menuType).orderByAsc(Menu::getOrderNo);
        List<Menu> menus = menuService.list(queryWrapper);
        return BeanUtil.copyToList(menus, MenuVO.class);
    }

    @GetMapping("role/keys/{roleId}")
    public List<String> queryMenuKeyByRole(@PathVariable String roleId){
        LambdaQueryWrapper<RoleMenu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RoleMenu::getRoleId, roleId);
        return roleMenuService.list(queryWrapper).stream().map(RoleMenu::getMenuId).toList();
    }

    @PostMapping("role/{roleId}")
    public void saveRoleMenuByRole(@PathVariable String roleId, @RequestBody List<String> menuIds){
        if(CollectionUtil.isEmpty(menuIds)){
            return;
        }
        permissionAuthService.saveRoleMenu(roleId, menuIds);
    }
}
